<style scoped>

</style>

<template>
  <div class="__function-view-con">
    <Card>
      <head-tool @on-add-function="handleAddFunction"/>

      <function-table :data="page.data"
                      :loading="tableLoading"
                      @on-update-function="handleUpdateFunction"
                      @on-remvoe-function="handleRemoveFunction"/>

      <Row type="flex" justify="end" style="margin-top: 20px;">
        <Col>
          <!-- 分页 -->
          <Page :current.sync="page.current"
                :page-size="page.pageSize"
                :total="page.total"
                @on-change="_handlePageChange"></Page>
        </Col>
      </Row>
    </Card>
  </div>
</template>

<script>
  import FunctionTable from './component/table'
  import HeadTool from './component/head-tool'
  import {mapState, mapActions} from 'vuex'
  import {_ChildLoading} from "_libs/util";

  export default {
    name: "FunctionView",
    data() {
      return {
        page: {
          current: 1,
          pageSize: 13,
          total: 0,
          data: []
        },
        tableLoading: false
      }
    },
    computed: {
      ...mapState('system', {
        tableData: state => state.function.functionList
      })
    },
    methods: {
      ...mapActions('system/function', [
        'listFunction',
        'addFunction',
        'updateFunction',
        'removeFunction'
      ]),
      // 更改分页数据
      changePageData() {
        let page = this.page
        page.data = []
        let start = (page.current - 1) * page.pageSize;
        let end = start + page.pageSize
        if (end >= this.tableData.length) {
          page.data = this.tableData.slice(start)
        }
        page.data = this.tableData.slice(start, end)
      },

      // 分页组件事件
      _handlePageChange() {
        this.changePageData();
      },

      // 添加功能
      handleAddFunction(funcitonForm, loadingCb) {
        let res = this.addFunction(funcitonForm);

        _ChildLoading(res, () => {
          this.changePageData()
          this.$Message.success('添加成功')
        }, loadingCb)
      },

      // 更新功能
      handleUpdateFunction(functionFom, loadingCb) {
        let res = this.updateFunction(functionFom);

        _ChildLoading(res, () => {
          this.$Message.success('更新成功')
        }, loadingCb)
      },

      // 删除功能
      handleRemoveFunction(func, loadingCb) {
        let res = this.removeFunction(func)

        _ChildLoading(res, () => {
          this.changePageData()
          this.$Message.success('删除成功')
        }, loadingCb)
      }
    },
    created() {
      this.tableLoading = true;
      this.listFunction().then(data => {
        this.page.total = data.length;
        this.changePageData();
        // 获取所有功能
        this.tableLoading = false;
      })
    },
    components: {
      FunctionTable,
      HeadTool
    }
  }
</script>
